<script lang="ts">
import {CreateKey} from "@/units/system";
import {defineComponent, PropType, reactive, computed, nextTick, ref, onUnmounted} from "vue";
import {useConfigure} from "@/apps/admin/hooks/configure";
import {useErrorDialog} from "@/hooks/DialogMsg";

export default defineComponent({
  name: "ChoiceMap",
  emits: ['update:modelValue', 'change', 'input'],
  props: {
    modelValue: Object as PropType<{ lng: string | number, lat: string | number }>,
    mapKey: {//地图授权KEY
      type: String
    },
    width: {//地图容器宽度
      type: String,
      default: '100%'
    },
    height: {//地图容器高度
      type: String,
      default: '420px'
    },
    disabled: {//禁用
      type: Boolean,
      default: false
    }
  },
  setup(props, {emit}) {
    const {conf} = useConfigure()

    /**
     * 地图窗口实例
     */
    const iframeWin = ref()

    /**
     * 位置数据
     */
    const data = reactive({error: '', src: ''})

    /**
     * 事件名称
     */
    const eventName = computed(() => {
      return CreateKey()
    })

    /**
     * 地图KEY
     */
    const loadMapKey = computed(() => {
      return props.mapKey ? props.mapKey : (conf?.map?.web_key)
    })

    /**
     * 位置信息描述
     */
    const pointInfo = computed(() => {
      if (props.modelValue.lng && props.modelValue.lat) {
        return `已选位置:${props.modelValue.lng},${props.modelValue.lat}`
      }
      return '请选择位置'
    })


    /**
     * 处理消息
     * @param result
     */
    function handleMessage(result: any) {
      const data = result.data ? JSON.parse(result.data) : {}
      if (data.event !== eventName.value) {
        return;
      }
      if (data.code === 200) {
        setValue(data.data.lng, data.data.lat)
      } else {
        useErrorDialog(data.msg)
      }
    }


    /**
     * 设置值
     */
    function setSrc() {
      if (props.modelValue.lng && props.modelValue.lat) {
        data.src = `components/choice-map.html?key=${loadMapKey.value}&event=${eventName.value}&lng=${props.modelValue.lng}&lat=${props.modelValue.lat}&uuid=` + CreateKey()
      } else {
        data.src = `components/choice-map.html?key=${loadMapKey.value}&event=${eventName.value}&lng=&lat=&uuid=` + CreateKey()
      }
    }

    /**
     * 清空值
     */
    function clearValue() {
      if (props.disabled) {
        return false;
      }
      setValue('', '')
      iframeWin?.value?.contentWindow?.clearMarker()
    }


    /**
     * 设置值
     * @param lng
     * @param lat
     */
    function setValue(lng: any, lat: any) {
      if (lng && lat) {
        lng = parseFloat(parseFloat(lng).toFixed(6))
        lat = parseFloat(parseFloat(lat).toFixed(6))
      }
      emit('update:modelValue', {lng, lat})
      emit('change', {lng, lat})
      emit('input', {lng, lat})
    }

    /**
     * 页面加载完毕事件
     */
    nextTick(() => {
      if (!loadMapKey.value) {
        data.error = '尚未配置腾讯地图KEY'
        return;
      }
      setSrc()
      window.addEventListener('message', handleMessage)
    })


    /**
     * 卸载页面事件
     */
    onUnmounted(() => {
      window.removeEventListener('message', handleMessage)
    })

    return {
      eventName, loadMapKey, pointInfo, data, iframeWin, clearValue
    }
  }
})
</script>

<template>
  <div class="show-box">
    <div v-if="data.error">
      <el-empty :description="data.error">
        <template #image>
          <svg-icon size="70" name="earth"></svg-icon>
        </template>
      </el-empty>
    </div>
    <div v-else>
      <el-input :value="pointInfo" readonly>
        <template #suffix>
          <el-text v-if="modelValue.lng && modelValue.lat" :type="disabled ? 'info' : 'danger'" class="app-tap" @click="clearValue">
            清除
          </el-text>
        </template>
      </el-input>
      <iframe ref="iframeWin" :width="width" :height="height" class="show-map" :src="data.src"></iframe>
    </div>
  </div>
</template>

<style scoped lang="scss">
.show-box {
  width: 100%;

  .show-map {
    box-sizing: border-box;
    border: 1px solid #d5d5d5;
    padding: 5px;
  }
}
</style>